import axios from 'axios'
import type {AxiosInstance, AxiosRequestConfig} from 'axios'
import type {responseType} from '@/api/type'
import {useUserStore} from "@/stores/user";
import {getToken} from './token'
import {ElMessage} from "element-plus";

const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    withCredentials: false,
    timeout: 3 * 1000
})

service.interceptors.request.use((config) => {
    config.headers['user-type'] = 'user'//表示该请求来自前台系统
    if (getToken()) {
        config.headers['token'] = getToken(); //携带token
        config.headers['Content-type'] = 'application/json';
    }
    return config;
}, (error) => {
    return Promise.reject(error)
})


service.interceptors.response.use((response) => {
    let {code, msg} = response.data
    switch (code) {
        case 200:
            if (response.config.method !== "get") {
                ElMessage({message: msg, type: 'success'})
            }
            break;
        case 401:
            ElMessage({message: msg || '登录过期', type: 'error'})
            const userStore = useUserStore()
            userStore.userLogout();
            break;
        default:
            console.log("请求异常")
            ElMessage({message: msg || '请求发生错误！', type: 'error'})
            return Promise.reject(msg)
    }
    return response.data;
}, (error) => {
    console.log("请求错误：", error)
    ElMessage({message: '服务器繁忙！', type: 'error'})
    return Promise.reject(error)
})

/**
 * 所有返回值类型为responseType{code,msg,data}，并允许对data指定类型
 * @param config
 * @returns
 */
export function request<T>(config: AxiosRequestConfig): Promise<responseType<T>> {
    return service(config);
}

export default request;
